package com.wzq.controller;


import com.wzq.controller.admin.GetSome;
import com.wzq.dao.dto.ProjectDto;
import com.wzq.dao.dto.ProjectDto2;
import com.wzq.dao.dto.StaticProjectDto;
import com.wzq.dao.pojo.*;
import com.wzq.dao.vo.ProjectVo;
import com.wzq.service.IDurationService;
import com.wzq.service.IProjectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzq.service.ITimeSelectionService;
import com.wzq.util.FrameUtil;
import com.wzq.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yzc
 * @since 2022-08-31
 */
@RestController
@RequestMapping("/project")
public class ProjectController extends GetSome {
    @Autowired
    private IProjectService iProjectService;
    //    添加活动
    @PostMapping("/activity")
    public Result saveActivity(@RequestBody StaticProjectDto projectDto) throws IOException {
        // 处理对象
        //添加项目
        Project project = new Project();
        project.setTitle(projectDto.getTitle());
        project.setAuthor(projectDto.getAuthor());
        project.setType(projectDto.getType());
        project.setContext(projectDto.getContext());
        project.setSpace(projectDto.getSpace());
        project.setBegintime(projectDto.getBegintime());
        project.setEndtime(projectDto.getEndtime());
        project.setApply(projectDto.getApply());
        boolean flag = iProjectService.save(project);
        Integer id = this.SelectIdByPro(projectDto);
        // 图片封面
        Image image = new Image();
        if (projectDto.getPicurl()!=null){
            image.setType((byte) 1);
            image.setUrl(projectDto.getPicurl());
            image.setP_id(id);
            iImageService.save(image);
        }
        //返回
        if (flag ){
            return new Result(Code.SAVE_OK,id);
        }
        return new Result(Code.SAVE_ERR,id);
    }
    //    添加资源
    @PostMapping
    public Result save(@RequestBody StaticProjectDto projectDto) throws IOException {
        // 处理对象
        // 判断必填项是否为空
        if("".equals(projectDto.getTitle()) || projectDto.getType()==null
                ||  "".equals(projectDto.getPicurl()) || projectDto.getPicurl()==null){
            return new Result(Code.SAVE_ERR,null);
        }
        //添加项目
        Project project = new Project();
        project.setTitle(projectDto.getTitle());
        project.setContext(projectDto.getContext());
        project.setMessage(projectDto.getMessage());
        project.setSpace(projectDto.getSpace());
        project.setType(projectDto.getType());
        project.setAuthor(projectDto.getAuthor());
        boolean flag = iProjectService.save(project);
        Integer id = this.SelectIdByPro(projectDto);

        // 添加t_image  静态资源路径
        String vidiourl = projectDto.getVidiourls()[0];
        // 图片封面
        Image image = new Image();
            image.setType((byte) 1);
            image.setUrl(projectDto.getPicurl());
            image.setP_id(id);
            iImageService.save(image);
        // 视频集合
        if (projectDto.getVidiourls()!=null && !"".equals(projectDto.getVidiourls()[0].trim())){
            image.setType((byte) 5);
            image.setUrl(vidiourl);
            image.setP_id(id);
            iImageService.save(image);
            // 视频封面
            //获取视频 的静态路径        "https://www.wulcl.cn:8055/mimi/upload/video/1670690977969.mp4"
            int i = vidiourl.lastIndexOf("/");
            //                  "https://www.wulcl.cn:8055/mimi/upload/video"
            String staticUrl = projectDto.getVidiourls()[0].substring(0, i);
            //  源视频文件URL    获取视频名(带'/'符号)        "/1670690977969.mp4"
            String vidioUrl = "C:/mimi/upload/video"+ vidiourl.substring(i);
            // 根据系统毫秒 生成图片封面文件名
            long time = System.currentTimeMillis();
            //  完整 图片保存URL
            String fileUrl ="C:/mimi/upload/video/img/" + time + ".jpg";
            //静态图片路径
            String staticName = staticUrl + "/img/" + time + ".jpg";
            boolean first = FrameUtil.getFirst(vidioUrl,fileUrl );
            if (first){
                image.setType((byte)4);
                image.setUrl(staticName);
                image.setP_id(id);
                iImageService.save(image);
            }
        }
            //添加t_duration
            Duration duration = new Duration();
            duration.setP_id(id);
            boolean duraFlag = iDurationService.save(duration);

            // 添加t_doorprojectDto
            DoorProject doorProject = new DoorProject();
            doorProject.setP_id(id);
            iDoorProjectService.save(doorProject);
            //返回
            if (flag  && duraFlag){
                return new Result(Code.SAVE_OK,id);
            }
        return new Result(Code.SAVE_ERR,id);
    }

    //    删除资源
    @DeleteMapping("/{id}")
    public Result removeById(@PathVariable int id){
        boolean flag = iProjectService.removeById(id);
        return new Result(flag? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    //根据用户ID，资源名称，删除资源
    @GetMapping("RemoveByIdAndTitle")
    public Result RemoveByIdAndSpaceName(@RequestParam("w_id") String w_id,@RequestParam("title") String title){
        LambdaQueryWrapper<Project> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectLambdaQueryWrapper.eq(Project::getAuthor,w_id);
        projectLambdaQueryWrapper.eq(Project::getTitle,title);
        boolean flag = iProjectService.remove(projectLambdaQueryWrapper);
        return new Result(flag? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    //    修改资源
    @PutMapping
    public Result updateById(@RequestBody Project project) {
        boolean flag = iProjectService.updateById(project);
        return new Result(flag? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    //    查询资源信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable int id){
        Project project = iProjectService.getById(id);
        int code = project !=null ? Code.GET_OK:Code.GET_ERR;
        String msg = project !=null ? "" : "数据查询失败，请重试！";
        return new Result(code, project,msg);
    }

    //查询资源的视频信息
    @GetMapping("vid/{id}")
    public Result getVidById(@PathVariable int id){
        List<Project> projectList = iProjectService.getVidById(id);
        if (projectList == null){
            System.out.println("null");
        }
        return new Result(Code.GET_OK, projectList,"查询成功");
    }

    //  根据活动类型查询
    @GetMapping("/type/{type}")
    public Result getByType(@PathVariable(value = "type") int type){
        LambdaQueryWrapper<Project> lqw = new LambdaQueryWrapper<>();
        System.out.println(type);
        lqw.eq(Project::getType,type);
        List<Project> list = iProjectService.list(lqw);
        return new Result(list!= null ? Code.GET_OK: Code.GET_ERR,list);
    }

    //  查询所有资源（设备）
    @GetMapping("/getresources")
    public Result getresources(){
        List<Project> projectList = iProjectService.SelectResources();
        System.out.println(projectList);
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //  搜索功能：按名字条件查询所有资源（设备）
    @GetMapping("/getResourcesByTitle")
    public Result getResourcesByTitle(@RequestParam("title") String title){
        List<Project> projectList = iProjectService.getResourcesByTitle(title);
        System.out.println(projectList);
        if (projectList.isEmpty()){
            return new Result(Code.GET_ERR,"暂无搜索结果");
        }
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //搜索功能：猜你需要（随机查三条资源[设备]）
    @GetMapping("/getResourcesRan")
    public Result getResourcesRan(){
        List<Project> projectList = iProjectService.getResourcesRan();
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //搜索功能：按名字条件查询所有活动
    @GetMapping("/getActivityByTitle")
    public Result getActivityByTitle(@RequestParam("title") String title){
        List<Project> projectList = iProjectService.getActivityByTitle(title);
        System.out.println(projectList);
        if (projectList.isEmpty()){
            return new Result(Code.GET_ERR,"暂无搜索结果");
        }
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //搜索功能：猜你需要随机查三条活动
    @GetMapping("/getActivityRan")
    public Result getActivityRan(){
        List<Project> projectList = iProjectService.getActivityRan();
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }



    //  根据空间名和用户ID 查询该用户下的所有资源（设备）
    @PostMapping("/getResourcesBySpaceNameAndUserId")
    public Result getResourcesBySpaceNameAndUserId(@RequestBody ProjectDto2 projectDto){
        List<ProjectDto> projectList = iProjectService.getResourcesBySpaceNameAndUserId(projectDto.getSpace_name(),projectDto.getW_id());
        System.out.println(projectList);
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //  查询所有活动
    @GetMapping("/getactivity")
    public Result getactivity(){
        List<Project> projectList = iProjectService.SelectActivity();
        System.out.println(projectList);
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //  查询所有活动
    @GetMapping("/find/getactivity")
    public Result FindGetActivity() throws Exception {
        // 判断活动是否结束
        isover();

        LambdaQueryWrapper<Project> lqw = new LambdaQueryWrapper<Project>();
        lqw.eq(Project::getIsover,0);
        lqw.orderByDesc(Project::getIstop).orderByDesc(Project::getLovenum).orderByAsc(Project::getPuttime);
        lqw.last("limit 10");
        List<Project> projectList = iProjectService.list(lqw);
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }

    //  实验室页查询所有活动
    @GetMapping("lab/getProject")
    public Result LabGetProject(){
        //所有活动
        List<Project> ActivityList = iProjectService.SelectActivity();
        //所有资源
        List<Project> ResourceList = iProjectService.SelectResources();
        //资源分类
        LambdaQueryWrapper<Type> Rwrapper = new LambdaQueryWrapper<>();
        Rwrapper.eq(Type::getParent,0);
        List<Type> RtypeList = iTypeService.list(Rwrapper);
        //活动分类
        LambdaQueryWrapper<Type> Awrapper = new LambdaQueryWrapper<>();
        Awrapper.eq(Type::getParent,1);
        List<Type> AtypeList = iTypeService.list(Awrapper);
        //用户分类
        List<Wechat_user> user = iWechat_userService.list();
        List<Wechat_user> User = new ArrayList<>();
        for ( Wechat_user w : user  ) {
            w.setType(w.getUsername());
            User.add(w);
        }

        //返回资源分类
        Map<String,Object> map = new HashMap<>();
        map.put("id",0);
        map.put("title","资源");
        map.put("children",RtypeList);

        //返回活动
        Map<String,Object> map1 = new HashMap<>();
        map1.put("id",1);
        map1.put("title","活动");
        map1.put("children",AtypeList);

        Map<String,Object> map2 = new HashMap<>();
        map2.put("id",2);
        map2.put("title","成员");
        map2.put("children",User);



        List<Object> objects = new ArrayList<>();
        objects.add(map);
        objects.add(map1);
        objects.add(map2);

        return  new Result(1,objects);

    }

    //     获得申请理由
    @GetMapping("/app/{w_id}")
    public Result getById(@PathVariable Integer w_id) throws Exception {
        isover();
        List<Member> active = new ArrayList<>();

        LambdaQueryWrapper<Member> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Member::getW_id,w_id);
        List<Member> list = iMemberService.list(lqw);
        for (Member member : list) {
            Project byId = iProjectService.getById(member.getP_id());
            if (byId.getIsover()==0) {
                member.setP_name(getP_name(member.getP_id()));
                active.add(member);
            }
        }
        Integer code = active != null ? Code.GET_OK : Code.GET_ERR;
        String msg = active != null ? "" : "数据查询失败，请重试！";
        return new Result(code,active,msg);
    }


    //按类型ID查询该类型下的所有项目
    @GetMapping("GetProjectByType")
    public Result GetProjectByType(@RequestParam ("id") Integer id){
        List<Project> projectList = iProjectService.GetProjectByType(id);
        if (projectList.isEmpty()){
            return new Result(Code.GET_ERR,null);
        }
        return new Result(Code.GET_OK,projectList);
    }

    @GetMapping("/getproject/{w_id}")
    public Result getProjectByTypeid(@PathVariable Integer w_id){
        List<Object> list=new ArrayList<>();
        List<Type> list1 = iTypeService.list();
        for (Type t : list1){
            Map<String, Object> map = new HashMap<>();
            map.put("id",t.getId());
            map.put("title",t.getType());
            //获取类型对应的   p_id
            LambdaQueryWrapper<Project> lqw = new LambdaQueryWrapper<>();
            lqw.select(Project::getId).eq(Project::getType,t.getId());
            List<Project> list2 = iProjectService.list(lqw);
            List<Integer> p_ids=new ArrayList<>();
            for (Project project : list2) {
                p_ids.add(project.getId());
            }
            //查询对应项目
            if (p_ids.size()>0){
                LambdaQueryWrapper<Mytrack> lqw1 = new LambdaQueryWrapper<>();
                lqw1.in(Mytrack::getP_id,p_ids);
                map.put("children", iMytrackService.list(lqw1));
                list.add(map);
                continue;
            }
            map.put("children", null);
            list.add(map);
        }
        return new Result(list.size()>0? Code.GET_OK: Code.GET_ERR,list);
    }

    //    查询所有资源
    @GetMapping
    public Result getAll(){
        List<Project> list = iProjectService.list();
        System.out.println(1);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }
    //    点赞
    @GetMapping ("{a}/love/{id}")
    public Result updatelove(@PathVariable int a,@PathVariable int id) {
        int flag = iProjectService.updateLove(a, id);
        return new Result(flag!=0?Code.LOVE_OK:Code.LOVE_ERR,a);
    }

    //根据插入资源信息查询该资源ID
    public Integer SelectIdByPro(Project project){
        LambdaQueryWrapper<Project> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Project::getTitle,project.getTitle()).eq(Project::getType,project.getType());
        Project SelectPro = iProjectService.getOne(lambdaQueryWrapper);
        Integer id = SelectPro.getId();
        return id;
    }


}


